
package com.gcloud.storage.service.impl;

import com.gcloud.core.exception.GCloudException;
import com.gcloud.header.compute.enums.FileFormat;
import com.gcloud.header.storage.StorageErrorCodes;
import com.gcloud.service.common.compute.uitls.DiskQemuImgUtil;
import com.gcloud.storage.StorageNodeProp;

import lombok.extern.slf4j.Slf4j;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class NodeVolumeServiceImpl {

    @Autowired
    private StorageNodeProp props;

    public void createDisk(String volumeId, String storageType, String poolName, Integer size) throws GCloudException {
        DiskQemuImgUtil.create(size, "G", this.genDiskPath(poolName, volumeId), FileFormat.QCOW2.getValue());
    }

    public void deleteDisk(String storageType, String poolName, String volumeId) throws GCloudException {
        String diskPath = this.genDiskPath(poolName, volumeId);
        File diskFile = new File(diskPath);
        if (diskFile.exists()) {
            if (!diskFile.delete()) {
                throw new GCloudException(StorageErrorCodes.FAILED_TO_DELETE_VOLUME);
            }
        }
    }

    public void resizeDisk(String storageType, String poolName, String volumeId, Integer oldSize, Integer newSize) throws GCloudException {
        String diskPath = this.genDiskPath(poolName, volumeId);
        this.checkAndGetFile(diskPath);
        DiskQemuImgUtil.resize(diskPath, newSize - oldSize);
    }

    private String genDiskPath(String poolName, String volumeId) {
        return poolName + volumeId;
    }

    private File checkAndGetFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            throw new GCloudException(StorageErrorCodes.FAILED_TO_FIND_VOLUME);
        }
        return file;
    }

}
